<template>
  <div class="roles">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="createUser">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" style="width: 100%" border stripe fit>
        <el-table-column type="expand">
          <!-- 展示角色权限 -->
          <template #default="scope">
            <el-row
              v-for="(i, index) in scope.row.children"
              :key="i.id"
              :class="['bd-bottom', index == 0 ? 'bd-top' : '', 'vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, i.id)"
                  >{{ i.authName }}<i class="el-icon-caret-right"></i
                ></el-tag>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row v-for="(item, index2) in i.children" :key="item.id">
                  <el-col
                    :class="[
                      'bd-bottom',
                      index2 == 0 ? 'bd-top' : '',
                      'vcenter',
                    ]"
                    :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item.id)"
                      >{{ item.authName
                      }}<i class="el-icon-caret-right"></i></el-tag
                  ></el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item2, index2) in item.children"
                      :key="item2.id"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}<i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="ID"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editCharactorInfo(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改弹窗区域 -->
    <el-dialog
      title="编辑"
      v-model="dialogFormVisible"
      @close="editDialogClose"
    >
      <el-form
        ref="editCharactorInfoRef"
        :model="currentUser"
        label-width="70px"
        :rules="currentUserRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="currentUser.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="currentUser.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="putEditCharactorInfo(currentUser.roleId)"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户弹窗区域 -->
    <el-dialog
      title="添加用户"
      v-model="createUserDialogVisible"
      @close="createDialogClose"
    >
      <el-form
        ref="createUserRef"
        :model="newUser"
        label-width="70px"
        :rules="newUserRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newUser.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="newUser.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="putCreateUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改权限对话框 -->
    <el-dialog
      title="编辑权限"
      v-model="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!-- 树形权限列表 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesList,
  deleteRoleUser,
  putCreateUser,
  deleteRolesById,
  getRightsList,
  appointRights
} from "@/network/power.js";

export default {
  name: "roles",
  data() {
    return {
      roleList: [], //列表数据
      rightList: [], //权限列表
      treeProps: {
        //树形控件的绑定参数
        label: "authName",
        children: "children",
      },
      defKeys: [], //默认选中的节点
      setRightDialogVisible: false,
      dialogFormVisible: false,
      createUserDialogVisible: false,
      currentUser: {
        //获取当前编辑的数据
        id: Number,
        roleName: "",
        roleDesc: "",
      },
      newUser: {
        roleName: "",
        roleDesc: "",
      },
      newUserRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 0,
            max: 10,
            message: "角色名称在零到十个字符之间",
            trigger: "blur",
          },
        ],
      },
      currentUserRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 0,
            max: 10,
            message: "角色名称在零到十个字符之间",
            trigger: "blur",
          },
        ],
      },
      roleId: Number,
    };
  },
  methods: {
    async getRolesList() {
      const { data: res } = await getRolesList();
      if (res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.roleList = res.data;
        // console.log(this.roleList);
      }
    },
    //修改角色信息
    async editCharactorInfo(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色参数失败");
      } else {
        this.currentUser = res.data;
        // console.log(this.currentUser);
        this.dialogFormVisible = true;
      }
    },

    // 确认修改信息并发送
    putEditCharactorInfo(id) {
      // console.log(typeof id);
      this.$refs.editCharactorInfoRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("输入非法");
          this.dialogFormVisible = false;
          return;
        } else {
          //发送请求修改数据
          this.dialogFormVisible = false;
          const { data: res } = await this.$http.put(`roles/${id}`, {
            roleId: id,
            roleName: this.currentUser.roleName,
            roleDesc: this.currentUser.roleDesc,
          });
          if (res.meta.status !== 200) {
            this.$message.error("编辑失败");
            // console.log(res);
          } else {
            this.$message.success("更新成功");
            this.getRolesList();
          }
        }
      });
    },

    //删除角色
    async deleteUser(id) {
      const { data: res } = await deleteRoleUser(id);
      if (res.meta.status !== 200) {
        this.$message.error("删除失败");
      } else {
        this.$message.success("删除成功");
        this.getRolesList();
      }
    },

    //添加角色
    createUser() {
      this.createUserDialogVisible = true;
    },

    //验证添加角色的信息是否合法并发送添加用户请求
    putCreateUser() {
      this.$refs.createUserRef.validate(async (valid) => {
        if (!valid) {
          // onsole.log("失败")
          this.$message.error("输入非法");

          this.createUserDialogVisible = false;
          return;
        } else {
          this.createUserDialogVisible = false;
          const { data: res } = await putCreateUser(this.newUser);
          console.log(res);
          if (res.meta.status !== 201) {
            return this.$message.error("添加失败");
          } else {
            this.$message.success("添加成功");
            this.getRolesList();
          }
        }
      });
    },
    //移除权限
    async removeRightById(roleId, rightId) {
      //弹框提示是否删除

      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      } else {
        const { data: res } = await deleteRolesById(roleId.id, rightId);
        if (res.meta.status !== 200) {
          console.log(res);
          return this.$message.error("删除权限失败");
        } else {
          roleId.children = res.data; //该请求的返回数据包括该角色的当前权限
          return this.$message.success("删除权限成功");
        }
      }
    },

    // 打开角色权限配置页
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await getRightsList("tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限树失败");
      } else {
        this.rightList = res.data;
        console.log(this.rightList);
        //获取三级节点的ID
        this.getLeafKeys(role, this.defKeys);
      }
      this.setRightDialogVisible = true;
    },

    //  获取角色下所有三级权限的ID
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },

    //分配权限页面关闭时处理
    setRightDialogClosed() {
      this.defKeys = [];
    },

    //发送权限修改请求
    async allotRights(){
      this.setRightDialogVisible = false;
      const key=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(key)
      const idStr = key.join(',')//join函数可以将数组以参数内的字符为分割，将数组转换为字符串
      const {data: res} = await appointRights(this.roleId,{rids: idStr});

      if(res.meta.status !== 200)
      {
        return this.$message.error("分配权限失败")
      }
      else{
        this.getRolesList();
        return this.$message.success("分配权限成功")
      }
    },
    //重置表单

    editDialogClose() {
      this.$refs.editCharactorInfoRef.resetFields();
    },
    createDialogClose() {
      this.$refs.createUserRef.resetFields();
    },
  },

  created() {
    this.getRolesList();
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
